import { createFiber } from "./createFiber";
import { isArray, isStr, updateNode } from "./utils/utils";


export function updateHostComponent(wip: any) {
    if(!wip.stateNode) {
        wip.stateNode = document.createElement(wip.type)
        updateNode(wip.stateNode, wip.props)
    }

    reconcileChildren(wip, wip.props.children)
}

export function updateFunctionComponent(wip: any) {
    const children = wip.type(wip.props)
    reconcileChildren(wip, children)
}

export function updateFragementComponent(wip: any) {
    const children = wip.type(wip.props)
    reconcileChildren(wip, children)
}


function reconcileChildren(returnFiber: any, children: any) {
  if (isStr(children)) {
    return;
  }
  const newChildren = isArray(children) ? children : [children];

  let previosNewFiber: null | IFiber = null;
  for (let i = 0; i < newChildren.length; i++) {
    const newChild = newChildren[i]
    const newFiber = createFiber(newChild, returnFiber)
    if(previosNewFiber === null) {
        returnFiber.child = newFiber
    }else{
        previosNewFiber.sibling = newFiber
    }
    previosNewFiber = newFiber
  }
}
